<!--
 * @Author: ygl
 * @Date: 2021-12-24 11:11:48
 * @LastEditors: ygl
 * @LastEditTime: 2021-12-27 17:42:20
 * @Description: file content
-->

<template>
  <div ref="line" :class="className" :style="{ height: height, width: width }" />
</template>

<script setup name='LineChart'>
import * as echarts from 'echarts'
import 'echarts/theme/macarons'
import Resize from './resize'

let chart = null
let line = ref(null)

let props = defineProps({
  className: {
    type: String,
    default: 'chart',
  },
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '350px',
  },
  autoResize: {
    type: Boolean,
    default: true,
  },
  chartData: {
    type: Object,
    // required: true,
    default: () => {},
  },
})

// 直接侦听一个 ref
watch(
  () => props,
  (newVal, oldVal) => {
    setOptions({ expectedData: newVal.chartData.expectedData, actualData: newVal.chartData.actualData })
  },
  {
    deep: true,
  }
)
onMounted(() => {
  nextTick(() => {
    initChart(line.value)
  })
})
onBeforeUnmount(() => {
  if (!chart) {
    return
  }
  chart.dispose()
  chart = null
})

function initChart(el) {
  chart = echarts.init(el, 'macarons')
  setOptions(props.chartData)
  let resetChart = new Resize(chart)
  resetChart.resetSize(chart)
}
function setOptions({ expectedData, actualData }) {
  chart.setOption({
    xAxis: {
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      boundaryGap: false,
      axisTick: {
        show: false,
      },
    },
    grid: {
      left: 10,
      right: 10,
      bottom: 20,
      top: 30,
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
      padding: [5, 10],
    },
    yAxis: {
      axisTick: {
        show: false,
      },
    },
    legend: {
      data: ['expected', 'actual'],
    },
    series: [
      {
        name: 'expected',
        itemStyle: {
          normal: {
            color: '#FF005A',
            lineStyle: {
              color: '#FF005A',
              width: 2,
            },
          },
        },
        smooth: true,
        type: 'line',
        data: expectedData,
        animationDuration: 2800,
        animationEasing: 'cubicInOut',
      },
      {
        name: 'actual',
        smooth: true,
        type: 'line',
        itemStyle: {
          normal: {
            color: '#3888fa',
            lineStyle: {
              color: '#3888fa',
              width: 2,
            },
            areaStyle: {
              color: '#f3f8ff',
            },
          },
        },
        data: actualData,
        animationDuration: 2800,
        animationEasing: 'quadraticOut',
      },
    ],
  })
}
</script>
